package com.wxtwxt.ruralmall.product.controller;

import java.util.Arrays;
import java.util.List;

import com.wxtwxt.ruralmall.common.utils.R;
import com.wxtwxt.ruralmall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.wxtwxt.ruralmall.product.entity.CategoryEntity;
import com.wxtwxt.ruralmall.product.service.CategoryService;

import javax.annotation.Resource;



/**
 * 商品三级分类
 *
 * @author Wxt
 * @email wxt23787@126.com
 * @date 2023-01-30 19:53:32
 */
@EnableTransactionManagement
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 查出所有分类以及子分类，以树形结构组装起来
     */
    @GetMapping("/list/tree")
    public R list(){
        List<CategoryEntity> categoryEntityList = categoryService.listWithTree();
        return R.ok().put("data", categoryEntityList);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId){
		CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("category", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CategoryEntity category){
		categoryService.save(category);

        return R.ok();
    }

    /**
     * 修改
     */
    @Caching(evict = {
            @CacheEvict(value = "category", key = "'findLevel1CateGorys'"),
            @CacheEvict(value = "category", key = "'getCateLogJson'"),
    })
    @Transactional
    @RequestMapping("/update")
    public R update(@RequestBody CategoryEntity category){
        if(StringUtils.isNotEmpty(category.getName())) {
            categoryBrandRelationService.updateCatelogName(category.getCatId(), category.getName());
        }
		categoryService.updateById(category);
        return R.ok();
    }

    @RequestMapping("/update/sort")
    public R update(@RequestBody CategoryEntity[] category){
        categoryService.updateBatchById(Arrays.asList(category));
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds){
        categoryService.removeMenusByIds(Arrays.asList(catIds));
        return R.ok();
    }

}
